﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.AspNet.Identity.Owin;
using AutoMapper;
using App.Core.Entities.Identity;
using App.Dto.Dtos.Identity;
using App.Core.Data.Repositories;
using App.Core.Data.Repositories.Identity;
using App.Core.Service.Identity;
using App.Core.Logging;
using App.Core.Cache;

namespace App.Web.Controllers
{
    [System.Web.Http.Authorize]
    [System.Web.Http.RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        #region 属性
        public ApplicationUserManager UserManager
        {
            get
            {
                return Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
        }

        public IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }
        readonly IMenuService iMenuService;
        readonly ILogger iLogger;
        readonly IUserCacheManager iUserCacheManager;

        #endregion

        public AccountController(IMenuService iMenuService,
            ILogger iLogger,
            IUserCacheManager userCacheManager)
        { 
            this.iMenuService = iMenuService;
            this.iLogger = iLogger;
            this.iUserCacheManager = userCacheManager;
        }
         
        public IHttpActionResult GetMenus()
        {
            this.iUserCacheManager.Reset();
            IList<MenuEntity> menuEntities = this.iMenuService.GetAll(); 

            IList<MenuEntity> mandatedMenu = new List<MenuEntity>();
            IDictionary<string, string> userModuleAuthMap = this.iUserCacheManager.GetAllModuleAuths();
            foreach (var item in menuEntities)
            {
                if (String.IsNullOrEmpty(item.View))
                {
                    mandatedMenu.Add(item);
                }
                else
                {
                    string[] moduleAuthArr = item.View.Split(';');
                    bool isAuth = false;
                    foreach (var moduleAuthItem in moduleAuthArr)
                    {
                        if (String.IsNullOrEmpty(moduleAuthItem) || moduleAuthItem.Length == 1 || isAuth)
                            continue;

                        string[] moduleAuthSplit = moduleAuthItem.Split('=');
                        string module = moduleAuthSplit[0];
                        string auths = moduleAuthSplit[1];

                        if (!userModuleAuthMap.ContainsKey(module))
                            continue;
                        string[] userAuths = userModuleAuthMap[module].Split(',');
                        string[] authArr = auths.Split(',');

                        if (userAuths.Any(x => authArr.Contains(x,StringComparer.OrdinalIgnoreCase)))
                        {
                            isAuth = true; 
                        }
                    }

                    if (isAuth)
                    {
                        mandatedMenu.Add(item);
                    } 
                }
            }

            mandatedMenu = mandatedMenu.OrderBy(x => x.SortNo).ToList();

            IList<MenuDto> menuDtos = new List<MenuDto>();
            Mapper.Map(mandatedMenu, menuDtos); 

            return Ok(menuDtos);
        } 

        //Logout
        //POST api/Account/Logout
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok();
        }
    }
}